package services

import (
	"fmt"
	"github.com/zhongshaofa/swan-jobs/internal/models"
	"github.com/zhongshaofa/swan-jobs/internal/repositorys"
	"github.com/zhongshaofa/swan-jobs/internal/request"
	"time"
)

type TaskInitService struct {
	pageLimit        int
	taskInterface    repositorys.TaskInterface
	CronManage       *CronTaskManage
	SupervisorManage *SupervisorTaskManage
}

func (t *TaskInitService) InitTask() {
	page := 1
	for true {
		list, _, err := t.taskInterface.GetList(
			&models.Task{Status: models.StatusEnable},
			request.PaginationRequest{
				Page:  page,
				Limit: t.pageLimit,
			},
		)
		if err != nil {
			fmt.Printf("InitTask error:%v", err)
			break
		}
		if len(list) == 0 {
			break
		}

		var appIds []int
		for _, t := range list {
			appIds = append(appIds, t.AppId)
		}

		for _, task := range list {
			if task.Mode == models.ModeCron {
				t.CronManage.Add(task)
			} else {
				t.SupervisorManage.Add(task)
			}
		}
		page++
	}

	go t.CronManage.Start()
	go t.SupervisorManage.Start()
	fmt.Println("InitTask:结束任务初始化")
}

func (t *TaskInitService) ListenSupervisorClientStatus() {
	for true {
		time.Sleep(5 * 1e9)
		if t.SupervisorManage == nil ||
			t.SupervisorManage.status == models.False ||
			t.SupervisorManage.Len() == 0 {
			continue
		}
		for _, supervisorTask := range t.SupervisorManage.list {
			go supervisorTask.UpdateTaskStatus()
		}
	}
}

// NewTaskInitService 初始化任务管理服务
func NewTaskInitService() *TaskInitService {
	return &TaskInitService{
		pageLimit:        20,
		taskInterface:    repositorys.TaskInterface(repositorys.TaskRepository{}),
		CronManage:       NewCronTaskManage(),
		SupervisorManage: NewSupervisorTaskManage(),
	}
}
